package com.zaozhuang.robot.websocket;


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zaozhuang.robot.MainActivity;
import com.zaozhuang.robot.R;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.UUID;

import javax.net.ssl.SSLParameters;

public class socketService extends Service {

    private static final String TAG = "socketService";
    private MessageListener messageListener;
    private static final long HEART_BEAT_RATE = 5 * 1000;//每隔5秒进行一次对长连接的心跳检测
    private final HeartHandler mHeartHandler = new HeartHandler(this);
    private WebSocketClient client;
    private String url;
    private String token;
    private Gson gson;
    private boolean isNewMessage = true;//标志是否是新的回答
    int i = 0;
    String uuid = UUID.randomUUID().toString();
    public socketService() {
    }

    public String getUUID(){
        return uuid;
    }
    private LocalBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder {

        public socketService getService() {
            return socketService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind: ");
        return mBinder;
    }

    @Override
    public void onCreate() {
        Log.i(TAG, "url: " + url);
        gson = new Gson();
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand:");
        url = intent.getStringExtra("url");
        token = intent.getStringExtra("token");
        if (client == null) {
            initSocketClient();
        }

        // 创建通知渠道
        String channelId = "websocket_id";
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //改为low取消通知提示音
            NotificationChannel channel = new NotificationChannel(channelId, "websocket_sustaining", NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(channel);
        }
        Intent intent2 = new Intent(socketService.this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(socketService.this, 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
        // 创建通知
        Notification notification = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notification = new Notification.Builder(this, channelId)
                    //                .setContentTitle("Your Notification Title")
                    .setContentText(getString(R.string.app_name) + "正在运行")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(pendingIntent)
                    .build();
        }
        startForeground(10000, notification);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
        try {
            Log.d(TAG, "onDestroy: socket service onDestroy()");
            client.close();
            mHeartHandler.removeCallbacksAndMessages(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRebind(Intent intent) {
        Log.i(TAG, "onRebind: ");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind: ");
        return super.onUnbind(intent);
    }

    private String lastMessageId = "-1";


    /**
     * 初始化webSocket
     */
    public void initSocketClient() {
//        String webSocketUrl = "ws://192.168.109.222:18007/webServer/123";
        String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        String targetUrl = url + uuid + "/?androidId=" + androidId;
        Log.i(TAG, "url:--" + targetUrl);

        try {
            client = new WebSocketClient(new URI(targetUrl), new Draft_6455()) {
                @Override
                public void onWebsocketPong(WebSocket conn, Framedata f) {
                    super.onWebsocketPong(conn, f);
                    Log.d(TAG, "onWebsocketPong: " + f.getPayloadData().toString());
                    Log.d(TAG, "onWebsocketPong: socket ping" + f.getOpcode());
                }

                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    // 连接打开以后的回调
                    Log.d(TAG, "onOpen: ");

                }

                @Override
                public void onMessage(String message) {
                    // 收到消息的回调
                    Log.d(TAG, "onMessage: socket接收服务器发来的消息:" + message);
                    if (message != null && !message.isEmpty()) {
                        if (message.contains(Constants.SocketMessageType.TYPE_ERROR)) {
                            if (messageListener != null) {
                                // 确保在主线程执行
                                new Handler(Looper.getMainLooper()).post(() -> {
                                    messageListener.onMessageReceived("思考时间太长了，请重新开始问答吧。");
                                });
                            }
                        }else if (message.contains(Constants.SocketMessageType.TYPE_WORKFLOW_STARTED)) {
                            if (messageListener != null) {
                                // 确保在主线程执行
                                new Handler(Looper.getMainLooper()).post(() -> {
                                    try {
                                        JSONObject jsonObject = new JSONObject(message);
                                        if (!lastMessageId.equals(jsonObject.getString("message_id"))) {
                                            messageListener.onMessageStart(jsonObject.getString("conversation_id"));
                                        }
                                        lastMessageId = jsonObject.getString("message_id");
                                    } catch (JSONException e) {
                                        throw new RuntimeException(e);
                                    }

                                });
                            }
                        } else if (message.startsWith("[") && message.endsWith("]")) {
                            List<SocketJobListEntity> jobList = gson.fromJson(message,
                                    new TypeToken<List<SocketJobListEntity>>() {
                                    }.getType());
                            if (messageListener != null) {
                                // 确保在主线程执行
                                new Handler(Looper.getMainLooper()).post(() -> {
                                    String introMsg = "";
                                    if (jobList.size() > 0) {
                                        introMsg = jobList.get(0).getIntro_msg();
                                    } else {
                                        introMsg = "未匹配到相应岗位,您可以进行求职发布";
                                    }
                                    messageListener.onJobListMessage(introMsg, jobList);
                                });
                            }
                        } else if (message.contains(Constants.SocketMessageType.TYPE_COMMAND)) {
                            SocketCommandEntity socketEntity = gson.fromJson(message, SocketCommandEntity.class);
                            if (messageListener != null) {
                                // 确保在主线程执行
                                new Handler(Looper.getMainLooper()).post(() -> {
                                    messageListener.onCommandReceived(socketEntity.getAnswer());
                                });
                            }
                        } else if (message.contains(Constants.SocketMessageType.TYPE_MESSAGE_TYPE)) {
                            SocketMessageTypeEntity socketEntity = gson.fromJson(message, SocketMessageTypeEntity.class);
                            if (messageListener != null) {
                                // 确保在主线程执行
                                new Handler(Looper.getMainLooper()).post(() -> {
                                    messageListener.onMessageTypeChanged(socketEntity.getAnswer());
                                });
                            }
                        } else if (message.contains(Constants.SocketMessageType.TYPE_MESSAGE)) {
                            SocketMessageEntity socketEntity = gson.fromJson(message, SocketMessageEntity.class);
                            Log.e(TAG, "onMessage message:" + message);
                            Log.e(TAG, "onMessage message message_id:" + socketEntity.getMessage_id());

                            if (messageListener != null) {
                                // 确保在主线程执行
                                new Handler(Looper.getMainLooper()).post(() -> {
                                    messageListener.onMessageReceived(socketEntity);
                                });
                            }
                        } else if (message.contains(Constants.SocketMessageType.TYPE_MESSAGE_END)) {
                            Log.e(TAG, "onMessage message end:" + message);
                            try {
                                SocketMessageEndEntity socketEntity = gson.fromJson(message, SocketMessageEndEntity.class);
                                Log.e(TAG, "onMessage message end message_id:" + socketEntity.getMessage_id());
                                if (messageListener != null) {
                                    // 确保在主线程执行
                                    new Handler(Looper.getMainLooper()).post(() -> {
                                        messageListener.onMessageReceived(socketEntity);
                                    });
                                }
                            } catch (Exception e) {
                                Log.e(TAG, "onMessage jsonparse Exception:");
                                if (messageListener != null) {
                                    // 确保在主线程执行
                                    new Handler(Looper.getMainLooper()).post(() -> {
                                        isNewMessage = true;
                                        messageListener.onMessageReceived(message);
                                    });
                                }
                            }
                        }

                    }
                }

                @Override
                public void onError(Exception ex) {
                    // 连接出错的回调
                    Log.d(TAG, "onError: " + ex);
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    // 连接关闭的回调， remote如果为true表示被服务端cut掉了
                    Log.d(TAG, "onClose reason: " + reason + "    remote: " + remote + "    code: " + code);
//                    client.close();
//                    mHeartHandler.removeCallbacksAndMessages(null);

                }

                @Override
                public void onMessage(ByteBuffer bytes) {
                    super.onMessage(bytes);
                    Log.d(TAG, "onMessage: socket bytebuffer bytes---" + bytes);
                }

                @Override
                protected void onSetSSLParameters(SSLParameters sslParameters) {
//                    super.onSetSSLParameters(sslParameters);
                    try {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            super.onSetSSLParameters(sslParameters);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };

//            wss的需要对client设置setSocketFactory()这个方法。
            mHeartHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
            client.addHeader("token", token);
            client.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过webSocket发送消息
     *
     * @param sMessage
     */
    public void sendMessage(String sMessage) {
        if (client == null || client.isClosed()) {
            Log.d(TAG, "sendMessage: client is null or closed");
            return;
        }
        try {
            client.send(sMessage);
            Log.d(TAG, "sendMessage: 发送---" + sMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 静态内部类Handler
     */
    private static class HeartHandler extends Handler {
        private final WeakReference<socketService> mService;

        public HeartHandler(socketService service) {
            this.mService = new WeakReference<>(service);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            socketService webSocketService = mService.get();
            if (webSocketService != null) {

            }
        }
    }

    //心跳线程
    private final Runnable heartBeatRunnable = new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "run: 扑通");
            if (client != null) {
                if (client.isClosed()) {
                    reconnectWs();
                    return;
                }
            } else {
                //如果client已为空，重新初始化websocket
                initSocketClient();
                return;
            }
            //定时对长连接进行心跳检测
            mHeartHandler.postDelayed(this, HEART_BEAT_RATE);
        }
    };

    /**
     * 开启重连
     */
    private void reconnectWs() {
        mHeartHandler.removeCallbacks(heartBeatRunnable);
        //重连
        mHeartHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
        client.reconnect();
        Log.d(TAG, "run: reconnectWs---心跳重连");

    }

    public interface MessageListener {
        void onMessageStart(String conversationId);

        void onMessageTypeChanged(String type);

        void onMessageReceived(Object socketEntity);

        void onCommandReceived(String answer);

        void onJobListMessage(String introMsg, List<SocketJobListEntity> jobList);
    }


    public void setMessageListener(MessageListener listener) {
        this.messageListener = listener;
    }
}
